package com.xh.controll;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xh.entiy.Course;
import com.xh.entiy.CourseCatalog;
import com.xh.entiy.CourseVideo;
import com.xh.entiy.Role;
import com.xh.entiy.TreeModel;
import com.xh.service.CatalogService;
import com.xh.service.CourseService;
import com.xh.service.CourseVidoeService;
import com.xh.service.RoleService;

@Controller
@RequestMapping("/admin")
public class AdminControl {

	@Autowired // 自动把接口实例化
	private CourseService courseService;
	@Autowired
	private CatalogService catalogService;
	@Autowired
	private CourseVidoeService courseVidoeService;
	@Autowired
	private RoleService roleService;
	

	@RequestMapping(value = "/savecourse", method = RequestMethod.POST) // 处理所有ajax中url为savecourse的请求
	@ResponseBody // 转化为json数据
	public Course saveCourse(Course course, HttpServletRequest request) {
		course = courseService.saveOrUpdate(course);// 传过来的课程调用saveorUpdate方法存储
		System.out.println(request.getServletContext().getRealPath("/admin"));
		return course;
	}

	@RequestMapping(value = "/getcourse", method = RequestMethod.GET)
	@ResponseBody
	public List<Course> getCourse() {
		System.out.println("**");
		List<Course> courses = courseService.getCourses();
		for (Course c : courses) {
			System.out.println(c.getId() + "  " + c.getName() + "  " + c.getDescript() + "  " + c.getCreate_time());
		}
		return courses;
	}

	@RequestMapping(value = "/getDescript", method = RequestMethod.POST)
	@ResponseBody
	public String getDescript(@RequestParam("catalogid") Integer id) {
		CourseCatalog catalog = catalogService.findById(id);
		String descript = catalog.getDescript();
		return descript;
	}

	@RequestMapping(value = "/saveCatalog")
	@ResponseBody
	public void saveCatalog(@RequestParam("cid") Integer cid, CourseCatalog catalog) {
		Course course = courseService.getCourse(cid);
		catalog.setCourse(course);
		System.out.println(course.getId() + "  " + catalog.getName());
		catalogService.saveCatalog(catalog);
	}

	@RequestMapping(value = "/deleteCatalog", method = RequestMethod.POST)
	@ResponseBody
	public void deleteCatalog(@RequestParam("cid") Integer cid, CourseCatalog catalog) {
		System.out.println("accept delete!");
		deleteCatalogs(catalog.getId());
	}

	private void deleteCatalogs(Integer id) {
		List<CourseCatalog> children = catalogService.findByParentId(id);
		if (children != null) {
			for (CourseCatalog c : children) {
				deleteCatalogs(c.getId());
			}
		}
		System.out.println("===>" + id);
		catalogService.deleteCatalogs(id);// 递归方法中调用catalogService的删除方法
	}

	@RequestMapping(value = "/getCTree/{id}")
	@ResponseBody
	public List<TreeModel> getCourseTree(@PathVariable("id") Integer id) throws JsonProcessingException {
		List<TreeModel> tm = new ArrayList<>();
		List<CourseCatalog> catalogs = catalogService.getCatalog(id);
		for (int i = 0; i < catalogs.size(); i++) {
			CourseCatalog cc = catalogs.get(i);
			if (cc.getParentId() == null) {
				TreeModel t = new TreeModel();
				t.setId(cc.getId());
				t.setText(cc.getName());
				t.setChildren(getchildren(cc.getId(), catalogs));
				tm.add(t);
			}
		}
		// System.out.println(objectMapper.writeValueAsString(tm));
		return tm;
	}

	private List<TreeModel> getchildren(Integer id, List<CourseCatalog> catalogs) {
		List<TreeModel> tmp = new ArrayList<>();
		for (CourseCatalog c : catalogs) {
			if (c.getParentId() == id) {
				TreeModel t = new TreeModel();
				t.setId(c.getId());
				t.setText(c.getName());
				t.setChildren(getchildren(c.getId(), catalogs));
				tmp.add(t);
			}
		}
		return tmp;
	}

	// 文件传输的代码
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(@RequestParam("currentclassid") Integer id, @RequestParam("multifile") MultipartFile file,HttpServletRequest request)
			throws UnsupportedEncodingException {
		System.out.println("**********");
		System.out.println("id=" + " +++++++++" + id);
		if (!file.isEmpty()) {
			String path=getPath(id);
			File f = new File("d:/course/"+path);
			String filename = new String(file.getOriginalFilename().getBytes("iso-8859-1"), "UTF-8");
			CourseVideo courseVideo=new CourseVideo();
			String descripition=request.getParameter("uploadfiledescripition");
			String name=request.getParameter("uploadfilename");
			String img=request.getParameter("img");
			CourseCatalog ccatalog=catalogService.findById(id);
			courseVideo.setCatalog(ccatalog);
			courseVideo.setName(name);
			courseVideo.setPath("d:/course/"+path+"/"+filename);
			courseVideo.setImg(img);
			courseVideo.setDescript(descripition);
			courseVideo.setUpload_time(new Date());
			courseVidoeService.saveOrupdate(courseVideo);

			if (!f.exists())
				f.mkdirs();
			try {
				
				BufferedOutputStream out = new BufferedOutputStream(
				new FileOutputStream(
				new File(f.getPath() + "/" + filename)));
				out.write(file.getBytes());
				out.flush();
				out.close();
				return "上传成功";
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "上传失败";
	}
	//递归寻找parentid和主要id
	private String getPath(Integer id) {
		String path="";
		CourseCatalog cctag=catalogService.findById(id);
		if(cctag.getParentId()!=null)
		{
			path=getPath(cctag.getParentId());
		}
		else {
			Course cou=cctag.getCourse();
			path=cou.getName();
		}
		return path+"/"+cctag.getName();
		
	}
	
	
	@RequestMapping(value="/showpath/{id}")
	public String showPath(@PathVariable("id") Integer id){
		String path="";
		CourseCatalog cc=catalogService.findById(id);
		if(cc.getParentId()==null){
			Course c=cc.getCourse();
			path=c.getName();
		}else{
			path=getPath(cc.getId());
		}
		return path+"/"+cc.getName();
	}
	
	@RequestMapping(value="/getshow")
	@ResponseBody
	public List<CourseVideo> getShow(){
		List<CourseVideo> courseVideo=courseVidoeService.getcourseVideos();
		return courseVideo;
	}
	//修改视频
	@RequestMapping(value="/editvideo")
	@ResponseBody
	public void editVideo(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String id=request.getParameter("id");
		String name=request.getParameter("name");
		String descript=request.getParameter("descript");
		System.out.println("id="+id);
		CourseVideo courseVideo=courseVidoeService.getcourseVideo(Integer.valueOf(id));
		courseVideo.setName(name);
		courseVideo.setDescript(descript);
		System.out.println(courseVideo.getId()+" "+courseVideo.getName()+" "+courseVideo.getDescript());
		courseVidoeService.saveOrupdate(courseVideo);
		}
	//删除视频
	@RequestMapping(value="/deletevideo")
	@ResponseBody
	public void deleteVideo(@RequestParam("id") Integer id){
		CourseVideo courseVideo=courseVidoeService.getcourseVideo(id);
		System.out.println(courseVideo.getId());
		courseVidoeService.deleteCoursevido(courseVideo.getId());
	}
	
	//创建角色
	@RequestMapping(value="/saverole")
	@ResponseBody
	public Role saveRole(Role role,HttpServletRequest request) throws UnsupportedEncodingException{
		request.setCharacterEncoding("utf-8");
		return roleService.saveOrUpdateRole(role);
	}
	
	@RequestMapping(value="getrole")
	@ResponseBody
	public List<Role> getRole(){
		List<Role> roles=roleService.getRoles();
		for (Role r : roles) {
			System.out.println(r.getId()+" "+r.getName());
		}
		return roles;
	}
	
}
